/*
 * @Author: 四川华西绿舍建材有限公司
 * @Date: 2023-10-22 15:10:36
 * @LastEditors: 陈波
 * @LastEditTime: 2024-05-09 19:34:29
 * @Description: 
 * @FilePath: \graDesign\src\request\http.ts
 */
import axios from 'axios'
import showCodeMessage from './code'
import { ElMessage, ElLoading } from 'element-plus'
import { nextTick } from 'vue'
// 错误提示信息：给用户看
import { showMessageBox, showNotification } from '@/utils/alertMsg'

let loadingRequestCount = 0
let loadingInstance: any = null
// 显示加载
export const showLoading = () => {
  if (loadingRequestCount === 0) {
    loadingInstance = ElLoading.service({
      // target: '.layout_container',
      text: '数据请求中,请稍等...',
      lock: true,
      fullscreen: true,
      background: 'rgba(0, 0, 0, 0.7)' // 背景黑色透明度0.7
    })
  }
  loadingRequestCount += 1
}
// 加载完毕
export const hideLoading = () => {
  if (loadingRequestCount <= 0) return
  loadingRequestCount -= 1
  if (loadingRequestCount === 0) {
    nextTick(() => {
      loadingInstance.close()
    })
  }
}

// 1. 创建axios对象
const service = axios.create({})

type statusType = 'start' | 'cancel';
const STATUS: statusType = 'start';

// 2. 请求拦截器
service.interceptors.request.use(config => {
  // showLoading();
  // let controller: AbortController = new AbortController();
  
  const token = localStorage.getItem('access-token');
  if(token) {
    config.headers["access-token"] = token;
  }
  config.headers["action"] = STATUS;
  // 传递token值
  return config
}, async (error) => {
  return await Promise.reject(error)
})

// 3. 响应拦截器
service.interceptors.response.use(response => {
  const { status, data } = response;
  const msg = showCodeMessage(status);
  console.log('status:', status)
  // 判断code码
  if(status != 200) {
    showMessageBox('error', msg);
    showNotification('error', '错误' , '网络出错啦')
  }
  if(data.code == 1011) {
    // 用户名或密码错误
    showNotification('error', '错误' , data.msg || '请求失败～')
  }
  if(data.code == 1014) {
    // token失效
    showNotification('error', '错误' , data.msg || '请求失败～')
    setTimeout(() => {
      window.location.href = '/404'
    }, 500)
  }

  // setTimeout(() => {
  //   hideLoading()
  // }, 200)
  return data
}, async (error) => {
  console.log('error', error)
  if(error.code == 'ERR_CANCELED') {
    console.log('请求被手动取消!')
  } else {
    showMessageBox('error', '服务异常，请联系管理员！')
  }
  return await Promise.reject(error);
})

export default service
